<!-- acm 产品库存列表 -->
<template>
  <!-- <doc-alert title="【库存】产品库存、库存明细" url="https://doc.iocoder.cn/acm/stock/" /> -->

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品" prop="productId">
        <InfiniteSelect
          v-model="queryParams.productId"
          :api="loadProductList"
          label-key="name"
          value-key="id"
          placeholder="请选择产品"
          class="!w-240px"
        />
        <!-- <el-select
          v-model="queryParams.productId"
          clearable
          filterable
          placeholder="请选择产品"
          class="!w-240px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      -->
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          clearable
          filterable
          placeholder="请选择仓库"
          class="!w-240px"
          :filter-method="handleFilterMethod"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['acm:stock:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['acm:stock:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="名称" align="center" prop="productName" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="规格" align="center" prop="standardName" />
      <el-table-column label="预警最大库存数量" align="center" prop="maxCount" />
      <el-table-column label="预警最小库存数量" align="center" prop="minCount" />
      <el-table-column
        label="库存量"
        align="center"
        prop="count"
        :formatter="erpCountColumnFormatter"
      />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <!-- v-hasPermi="['erp:stock:update']" -->
          <el-button link type="primary" @click="openForm('update', scope.row.id)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑/新增弹窗 -->
    <Dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      style="min-width: 600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        v-loading="formLoading"
      >
        <el-form-item label="预警最大库存数量" prop="maxCount">
          <el-input
            v-model="formData.maxCount"
            type="number"
            step="1"
            placeholder="请输入预警最大库存数量"
            @input="handleIntegerInput('maxCount')"
          />
        </el-form-item>
        <el-form-item label="预警最小库存数量" prop="minCount">
          <el-input
            v-model="formData.minCount"
            type="number"
            step="1"
            placeholder="请输入预警最小库存数量"
            @input="handleIntegerInput('minCount')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { StockApi, StockVO } from '@/api/acm/stock/stock'
import { OnboardSupplyApi, OnboardSupplyVO } from '@/api/acm/onboardsupply'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/acmWarehouse'
import { erpCountColumnFormatter } from '@/utils'

/** acm 产品库存列表 */
defineOptions({ name: 'AcmStock' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<StockVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined,
  warehouseId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<OnboardSupplyVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StockApi.getStockPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 弹窗相关状态
const formRef = ref()
const formLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('') // 动态设置弹窗标题（新增/编辑）
const formData = reactive({
  id: undefined,
  maxCount: undefined,
  minCount: undefined
})

/** 表单校验规则：整数限制 + max>min 校验 */
const formRules = reactive({
  maxCount: [
    { required: true, message: '预警最大库存数量不能为空', trigger: ['blur', 'change'] },
    { type: 'integer', message: '预警最大库存数量必须为整数', trigger: ['blur', 'change'] },
    {
      validator: (rule: any, value: number, callback: any) => {
        // 当最小库存已输入时，校验最大库存必须大于最小库存
        if (formData.minCount !== undefined && formData.minCount !== null) {
          if (value <= formData.minCount) {
            callback(new Error('预警最大库存数量必须大于预警最小库存数量'))
          }
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  minCount: [
    { required: true, message: '预警最小库存数量不能为空', trigger: ['blur', 'change'] },
    { type: 'integer', message: '预警最小库存数量必须为整数', trigger: ['blur', 'change'] },
    {
      validator: (rule: any, value: number, callback: any) => {
        // 当最大库存已输入时，校验最小库存必须小于最大库存
        if (formData.maxCount !== undefined && formData.maxCount !== null) {
          if (value >= formData.maxCount) {
            callback(new Error('预警最小库存数量必须小于预警最大库存数量'))
          }
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ]
})

/** 整数输入过滤：防止输入非数字/小数 */
const handleIntegerInput = (field: 'maxCount' | 'minCount') => {
  const value = formData[field]?.toString() || ''
  const pureNumber = value.replace(/[^0-9]/g, '')
  formData[field] = Number(pureNumber)
}

/** 打开弹窗（区分新增/编辑） */
const openForm = async (type: 'create' | 'update', id?: number) => {
  // 1. 重置表单状态（清除历史数据和校验）
  formData.id = undefined
  formData.maxCount = undefined
  formData.minCount = undefined
  formRef.value?.resetFields()

  // 2. 设置弹窗标题和显示
  dialogTitle.value = type === 'create' ? '新增库存预警' : '编辑库存预警'
  dialogVisible.value = true

  // 3. 加载已有数据
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      const res = await StockApi.getStock(id)
      formData.id = res.id
      formData.maxCount = res.maxCount
      formData.minCount = res.minCount
    } catch (error) {
      message.error(t('common.getInfoFailed')) // "获取数据失败"
      dialogVisible.value = false // 加载失败关闭弹窗
    } finally {
      formLoading.value = false
    }
  }
}

/** 关闭弹窗：清除校验状态和表单数据 */
const handleDialogClose = () => {
  formRef.value?.resetFields() // 清除表单校验红框/错误提示
  // 重置表单数据（避免下次打开残留）
  formData.id = undefined
  formData.maxCount = undefined
  formData.minCount = undefined
}

/** 提交表单（新增/编辑） */
const submitForm = async () => {
  // 1. 表单校验
  await formRef.value.validate()

  // 2. 提交请求
  formLoading.value = true
  try {
    const submitData = { ...formData }
    if (formData.id) {
      // 编辑：调用更新接口
      await StockApi.updateStockCount(submitData)
      message.success(t('common.updateSuccess')) // "修改成功"
    } else {
      await StockApi.createStock(submitData)
      message.success(t('common.createSuccess')) // "创建成功"
    }
    // 3. 关闭弹窗并刷新列表
    dialogVisible.value = false
    await getList() // 提交成功后刷新库存列表
  } catch (error) {
    message.error(t('common.operateFailed')) // "操作失败"
  } finally {
    formLoading.value = false
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StockApi.exportStock(queryParams)
    download.excel(data, '机供品库存.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleFilterMethod = async (query?: string) => {
  console.log('filtering with query:', query)
  const data = await WarehouseApi.getWarehouseSimpleList()
  if (!query) {
    warehouseList.value = data.slice(0, 200)
    return warehouseList.value
  }
  warehouseList.value = data.filter((d) => d.name.toLowerCase().includes(query.toLowerCase()))
  return warehouseList.value
}

const loadProductList = async () => {
  return await OnboardSupplyApi.getOnboardSupplySimpleList({ category: '', name: '' })
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表
  handleFilterMethod()
  // productList.value = await OnboardSupplyApi.getOnboardSupplySimpleList({ category: '', name: '' })
  // warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
})
</script>
